package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    //导入菜品的service
    @Autowired
    private DishService dishService;
    //导入套餐的service
    @Autowired
    private SetmealService setmealService;

    /**
     * 根据id删除分类，删除之前需要判断该类有关联
     * @param id
     */
    @Override
    public void remove(Long id) {
        //如果该类关联了菜品那就抛出异常
        //添加条件 用id来查询
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        //调用方法来查询是否关联了菜品
        int dishCount = dishService.count(dishLambdaQueryWrapper);
        if(dishCount>0){
            //已经关联了菜品
            throw new CustomException("该类关联了菜品,删除失败");
        }
        //如果该类关联了套餐那就抛出异常
        //添加条件 用id来查询
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        //调用方法来查询是否关联了套餐
        int setmealCount = dishService.count(dishLambdaQueryWrapper);
        if(setmealCount>0){
            //已经关联了套餐
            throw new CustomException("该类关联了套餐,删除失败");
        }
        //可以正常删除
        super.removeById(id);
    }
}
